package com.android.sq.zouqi.main;

import java.util.LinkedList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.android.sq.zouqi.Constants;
import com.android.sq.zouqi.R;
import com.android.sq.zouqi.bdmap.BMapApp;
import com.android.sq.zouqi.bdmap.pScrEventMap;
import com.android.sq.zouqi.event.pCtrlEventInfo;
import com.android.sq.zouqi.event.pScrEventInfo;
import com.android.sq.zouqi.event.pTableEventInfo;
import com.android.sq.zouqi.pushservice.PushService;
import com.android.sq.zouqi.relationship.pCtrlRelation;
import com.android.sq.zouqi.relationship.pInviteFriend;
import com.android.sq.zouqi.relationship.pTableRelation;

/*
 * 以显示活动列表数据为例，主要是调用方法pShowEventInterface,
 * 在这个方法内有一个线程switch_func_thread，
 * 通过构造方法传递给它信号showEventInterface_signal，
 * 在run方法根据这个信号，调用pShowEventList来获取服务端的数据，
 * 当获取完毕，发送信号showEventInterface_signal给handler，
 * handler根据信号进行UI更新
 */

public class pScrMain extends TabActivity {
	private final static String TAG = "pScrMain";
	private Context context;
	private SharedPreferences share;

	//ScrollView上面的新建按钮
	private LinearLayout layout;
	private ImageView pImgNewThing;
	private Bitmap new_event_bmp, invite_friend_bmp;
	
	// 活动
	private ListView pListNewInvite, pListRolling, pListUnstarted;
	
	private LinkedList<pTableEventInfo> unconfirm_list, rolling_list, unstart_list; 
	private EventLVAdapter unconfirm_adapter, rolling_adapter, unstart_adapter;
	// 好友
	private ListView pListNewFriends, pListFriends;
	private LinkedList<pTableRelation> newfriends_list, friends_list;
	private FriendLVAdapter newfriends_adapter, friends_adapter;
	// 历史记录
	private ListView pListFinished, pListCancelled;
	private LinkedList<pTableEventInfo> finished_list, cancelled_list;
	private EventLVAdapter finished_adapter, cancelled_adapter;
	
	private pCtrlEventInfo ctrl_event;
	private pCtrlRelation ctrl_relation;
	private int user_id;
	
	private TabHost tab_host;
	
	private static String Friend_Tag = "friend_tag";
	private static String Event_Tag = "event_tag";
	private static String History_Tag = "history_tag";
	
	private SwitchFuncThread switch_func_thread;
	private final int showEventInterface_signal = 0;
	private final int showFriendsInterface_signal = 1;
	public static final int showHistoryInterface_signal = 2;
	
	private final int confirmEventInvite_signal = 3;
	private final int confirmFriendInvite_signal = 4;
	
	private final int cancelEvent_signal = 5;
	
	// 通知栏相关的信号 -  已转移到Constants类中
	/*public static final int notify_show_histroy_signal = 6;
	public static final int notify_new_event_signal = 7;		// 当收到主题<zouqi/*id*>的消息<new_event:*id*>
	public static final int notify_event_change_signal = 9;		// 当收到某一个活动的推送<zouqi/event_*id*>*/
	
	// 通知switchToFuncThread进行消息订阅，主要用于当加载活动列表时，订阅相关的活动主题<zouqi/event_*id*>
	public static final int subscribe_signal = 8;				
	
	public static boolean from_notify = false;
	
	// 一些变量
	public boolean event_interface_reflash = true;		// 第一次加载需要刷新数据
	public boolean friend_interface_reflash = true;
	public boolean history_interface_reflash = true;
	
	/*
	 * Activity
	 */
	
	private final static int ScrEventInfo = 1;
	private int current_event_id = 0;							// 当前被确认活动邀请的id
	private pTableEventInfo current_event;
	private pTableRelation confirmFriendsInvite_relation = null;// 确认好友邀请的pTableRelation对象
	
	// menu的一些变量
	private Dialog confirmCancelDialog = null;
	private static final int CONFIRM_CANCEL_DIALOG = 1;
	
	public Handler appHandler;
	
	public Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case showEventInterface_signal:
				//分别用以上数据填充各自的adapter并匹配到相应的list中;
				unconfirm_adapter = new EventLVAdapter(pScrMain.this, 
						unconfirm_list, R.layout.scrmain_event_new_event_item);
				rolling_adapter = new EventLVAdapter(pScrMain.this,
						rolling_list, R.layout.scrmain_event_rolling_event_item);
				unstart_adapter = new EventLVAdapter(pScrMain.this,
						unstart_list, R.layout.scrmain_event_unstart_event_item);
				pListNewInvite.setAdapter(unconfirm_adapter);
				setListViewHeightBasedOnChildren(pListNewInvite);
				pListRolling.setAdapter(rolling_adapter);
				setListViewHeightBasedOnChildren(pListRolling);
				pListUnstarted.setAdapter(unstart_adapter);
				setListViewHeightBasedOnChildren(pListUnstarted);
				break;
			case showFriendsInterface_signal:
				Log.e(TAG, "handler 处理展示好友列表");
				newfriends_adapter = new FriendLVAdapter(pScrMain.this,
						newfriends_list, R.layout.scrmain_friend_new_friends_item);
				Log.e(TAG, "newfriends_adapter 初始化完成");
				friends_adapter = new FriendLVAdapter(pScrMain.this,
						friends_list, R.layout.scrmain_friend_friends_item);
				pListNewFriends.setAdapter(newfriends_adapter);
				Log.e(TAG, "把适配器放进ListView中");
				setListViewHeightBasedOnChildren(pListNewFriends);
				pListFriends.setAdapter(friends_adapter);
				setListViewHeightBasedOnChildren(pListFriends);
				break;
			case showHistoryInterface_signal:
				Log.e("pScrMain", "handle history");
				finished_adapter = new EventLVAdapter(pScrMain.this,
						finished_list, R.layout.scrmain_history_finish_event_item);
				Log.e("pScrMain", "handle history finished");
				cancelled_adapter = new EventLVAdapter(pScrMain.this,
						cancelled_list, R.layout.scrmain_history_cancel_event_item);
				
				pListFinished.setAdapter(finished_adapter);
				setListViewHeightBasedOnChildren(pListFinished);
				pListCancelled.setAdapter(cancelled_adapter);
				setListViewHeightBasedOnChildren(pListCancelled);
				break;
			case confirmEventInvite_signal :
				pShowEventInterface();
				break;
			case confirmFriendInvite_signal :
				pShowFriendsInterface();
				break;
			case cancelEvent_signal :
				// 取消活动之后刷新列表
				pShowEventInterface();
				break;
			/*case notify_show_histroy_signal :
				Log.e("pScrMain", "收到来自推送的消息");
				from_notify = true;
			case notify_new_event_signal :
				// 因为必须要在另外一个线程里才能订阅，所以不能放在PushService中进行
				String msg_content = (String)msg.obj;
				Log.e(TAG, "handler内 - msg_content = " + msg_content);
				switch_func_thread = new SwitchFuncThread(subscribe_signal, PushService.MQTT_TOPIC + "/event_" + msg_content);
				switch_func_thread.start();
				event_interface_reflash =  true;
				//notifyNewEvent(msg_content);
				break;
			case notify_event_change_signal :
				int event_id = (Integer)msg.obj;
				break;*/
			default :
				break;
			}
		}
	};
	
	public void notifyNewEvent(String msgContent) {
		Log.e(TAG, "方法notifyNewEvent - msg_content = " + msgContent);
		switch_func_thread = new SwitchFuncThread(subscribe_signal, PushService.MQTT_TOPIC + "/event_" + msgContent);
		switch_func_thread.start();
		event_interface_reflash =  true;
	}
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e("pScrMain", "on Create");
		setContentView(R.layout.main_pscrmain);
		
		this.context = this.getApplicationContext();
		
		BMapApp app = (BMapApp) this.getApplication();
		app.setActivityInfo(Constants.ACTIVITY_pScrMain, null);
		
		//this.appHandler = app.handler;
		app.scrMain = this;
		
		Log.e(TAG, "app.scrMain toString = " + app.scrMain.toString());
		Log.e(TAG, "app.scrMain hashCode = " + app.scrMain.hashCode());
		share = context.getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
		user_id = share.getInt(Constants.SP_USER_ID, 0);
		ctrl_event = new pCtrlEventInfo(context, handler);
		ctrl_relation = new pCtrlRelation(context, handler);
		
		tab_host = this.getTabHost();
		
		tab_host.addTab(tab_host.newTabSpec(Event_Tag).setIndicator("活动").setContent(R.id.Event_Tag));
		tab_host.addTab(tab_host.newTabSpec(Friend_Tag).setIndicator("好友").setContent(R.id.Friend_Tag));
		tab_host.addTab(tab_host.newTabSpec(History_Tag).setIndicator("历史").setContent(R.id.History_Tag));
		
		
		/*
		 * 需要针对是否标签页内容有过修改，决定是否重新加载数据，需要增加一个标志位
		 */
		tab_host.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tag) {
				// TODO Auto-generated method stub
				if (tag.equals(Friend_Tag)) {
					Log.e(TAG, "收到切换到好友栏的信号");
					pShowFriendsInterface();
				} else if (tag.equals(Event_Tag)) {
					pShowEventInterface();
				} else if (tag.equals(History_Tag)) {
					Log.e("pScrMain", "收到切换信号");
					pShowHistoryInterface();
				}
			}
		});
		LayoutInflater inflater = (LayoutInflater) pScrMain.this.getSystemService(LAYOUT_INFLATER_SERVICE);
		layout = (LinearLayout)inflater.inflate(R.layout.main_pscrmain, layout); 
		
		pImgNewThing = (ImageView) findViewById(R.id.new_img);
		new_event_bmp = BitmapFactory.decodeResource(getResources(), R.drawable.new_event);
		invite_friend_bmp = BitmapFactory.decodeResource(getResources(), R.drawable.invite_friend);
		
		pImgNewThing.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Log.e("pScrMain", "new_event id = " + R.drawable.new_event + ", invite_friend id = " + R.drawable.invite_friend);
				//Log.e("pScrMain", "pImgNewThing.id = " + pImgNewThing.getId());
				int img_id = pImgNewThing.getId();
				switch (img_id) {
				case R.drawable.new_event :
					/*
					 *  因为创建新活动跳转之后，并不一定会创建，或许会直接返回，
					 *  所以reflash信号在pNewEvent中完成之后再设置，
					 *  然后onResume根据reflash决定是否活动列表数据
					 */
					pNewEvent();
					break;
				case R.drawable.invite_friend :
					pAddFriends();
					break;
				default :
					break;
				}
			}
		});
		pShowEventInterface();
		Log.e("pScrMain", "onCreate- event_interface_reflash = " + event_interface_reflash );
		//PushService.handler = this.handler;
		//Log.e(TAG, "PushService.handler = app.getHandler()");
		//PushService.handler = this.handler;
	}
	
	/*
	 * 当用户点击了新活动按钮，即切到了创建新活动的Act，
	 * 当它创建活动成功返回到pScrMain，根据reflash的值，
	 * 决定是否刷新列表信息，因此也把reflash的值设置成public static
	 */
	@Override
	public void onResume() {
		super.onResume();
		Log.e("pScrMain", "on Resume - event_interface_reflash = " + event_interface_reflash );
		if (from_notify) {
			Log.e("pScrMain", "onResume switch to histor tag");
			tab_host.setCurrentTabByTag(History_Tag);
		}
		
		if (event_interface_reflash) {
			Log.e("pScrMain", "活动列表要更新，进行刷新鸟");
			pShowEventInterface();
			tab_host.setCurrentTabByTag(Event_Tag);
		} 
	}
	
	@Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {   
        // TODO Auto-generated method stub   
        super.onActivityResult(requestCode, resultCode, data);   
        Log.e(TAG, "---onActivityResult---从上一个界面pScrEventInfo返回, requestCode = " + requestCode + ", resultCode = " + resultCode);
        switch(requestCode) {   
        case ScrEventInfo: //执行成功，返回  
        	// 在pScrChooseLocation界面按了返回键
        	if (resultCode == 0) {
        		Log.e(TAG, "直接返回");
        	}
        	// 在pScrEventInfo界面按了保存
        	else if (resultCode == -1) {
        		Log.e(TAG, "保存返回");
        		if (data != null) {
        			Bundle bundle = data.getExtras();       //获取intent里面的bundle对象   
        			int refresh_type = bundle.getInt("REFRESH_TYPE");
        			event_interface_reflash = true;
        			Log.e(TAG, "赋值给活动刷新标识为true");
                }
        	}
            break; 
        default:   
        	break;   
        }   
    }  
	
	//关于活动
	/*
	 * 显示活动列表界面 - pCB02F01
	 * 切换到活动列表标签页并调用pCB02F02填充数据
	 */
	public void pShowEventInterface() {
		
		pImgNewThing.setVisibility(View.VISIBLE);
		pImgNewThing.setImageBitmap(new_event_bmp);
		pImgNewThing.setId(R.drawable.new_event);
		
		if (event_interface_reflash) {
			Log.e("pScrMain", "pScrMain->pShowEventInterface");
			pListNewInvite = (ListView) findViewById(R.id.newevent_lv);
			pListRolling = (ListView) findViewById(R.id.rollingevent_lv);
			pListUnstarted = (ListView) findViewById(R.id.unstartevent_lv);
			
			/*Log.e("pScrMain", "pListNewInvite = " + pListNewInvite.getId());
			Log.e("pScrMain", "pListRolling = " + pListRolling.getId());
			Log.e("pScrMain", "pListUnstarted = " + pListUnstarted.getId());*/

			pListNewInvite.setOnItemClickListener(click_listener);
			pListRolling.setOnItemClickListener(click_listener);
			pListUnstarted.setOnItemClickListener(click_listener);
			pListNewInvite.setOnItemLongClickListener(longclick_listener);
			pListRolling.setOnItemLongClickListener(longclick_listener);
			pListUnstarted.setOnItemLongClickListener(longclick_listener);
			
			registerForContextMenu(pListNewInvite);
			registerForContextMenu(pListRolling);
			registerForContextMenu(pListUnstarted);
			
			switch_func_thread = new SwitchFuncThread(showEventInterface_signal);
			switch_func_thread.start();
			event_interface_reflash = false;
		}
	}
	
	/*
	 * pCB02F02 - 显示活动列表
	 * 一共取得三组数据并填充list，
	 * 分别是为接受邀请的活动列表、正在进行的活动列表、未开始的活动列表。
	 */
	public void pShowEventList() {
		Log.e("pScrMain", "获取 活动 列表数据");
		//获得未接受邀请的活动列表数据
		unconfirm_list = ctrl_event.pGetEventUnconfirmed(user_id);	
		//获得正在进行的活动列表数据
		rolling_list = ctrl_event.pGetEventList(user_id, Constants.EVENT_STATE_ROLLING);	
		//获得未开始的活动列表数据
		unstart_list = ctrl_event.pGetEventList(user_id, Constants.EVENT_STATE_UNSTARTED);
			
		handler.sendEmptyMessage(showEventInterface_signal);
	}
	
	// 关于好友
	/*
	 * 显示好友列表界面 - pCB02F05
	 * 切换到好友列表标签并调用pCB02F06填充数据。
	 */
	public void pShowFriendsInterface() {
		pImgNewThing.setVisibility(View.VISIBLE);
		pImgNewThing.setImageBitmap(invite_friend_bmp);
		pImgNewThing.setId(R.drawable.invite_friend);
		
		if (friend_interface_reflash) {
			pListNewFriends = (ListView) findViewById(R.id.newfriends_lv);
			pListFriends = (ListView) findViewById(R.id.friends_lv);
		
			Log.e("pScrMain", "pListNewFriends = " + pListNewFriends.getId());
			Log.e("pScrMain", "pListFriends  = " + pListFriends.getId());

			/*pListNewFriends.setOnItemClickListener(click_listener);
			pListFriends.setOnItemClickListener(click_listener);
			pListNewFriends.setOnItemLongClickListener(longclick_listener);
			pListFriends.setOnItemLongClickListener(longclick_listener);*/
			
			switch_func_thread = new SwitchFuncThread(showFriendsInterface_signal);
			switch_func_thread.start();
			friend_interface_reflash = false;
		}
	}

	// 关于历史记录
	/*
	 * 显示历史活动列表界面 - pCB02F03
	 * 切换到历史活动列表标签页并调用pCB02F04填充数据
	 */
	public void pShowHistoryInterface() {
		layout.setVisibility(View.INVISIBLE);
		pImgNewThing.setVisibility(View.INVISIBLE);
		
		if (history_interface_reflash) {
			Log.e("pScrMain", "reflash = true");
			pListFinished = (ListView) findViewById(R.id.finished_lv);
			pListCancelled = (ListView) findViewById(R.id.cancelled_lv);
			
			Log.e("pScrMain", "pListFinished = " + pListFinished.getId());
			Log.e("pScrMain", "pListCancelled = " + pListCancelled.getId());
			
			pListFinished.setOnItemClickListener(click_listener);
			pListCancelled.setOnItemClickListener(click_listener);
			pListFinished.setOnItemLongClickListener(longclick_listener);
			pListCancelled.setOnItemLongClickListener(longclick_listener);
			
			switch_func_thread = new SwitchFuncThread(showHistoryInterface_signal);
			switch_func_thread.start();
			history_interface_reflash = false;
			from_notify = false;
		}
	}

	/*
	 * 显示历史活动列表 - pCB02F04
	 * 一共取得两组数据并填充list，分别是已经结束的活动列表、已经取消的活动列表
	 */
	public void pShowHistoryList() {
		Log.e("pScrMain", "获取 历史 列表数据");
		//获得顺利完成的活动列表数据
		finished_list = ctrl_event.pGetEventList(user_id, Constants.EVENT_STATE_FINISHED);	
		//获得取消的活动列表数据
		cancelled_list = ctrl_event.pGetEventList(user_id, Constants.EVENT_STATE_CANCELLED);	
		handler.sendEmptyMessage(showHistoryInterface_signal);
	}
	
	/*
	 * 显示好友列表 - pCB02F06
	 * 取得好友数据并填充list
	 */
	public void pShowFriendsList() {
		// 获得好友邀请列表数据;
		Log.e("pScrMain", "获取 好友邀请 列表数据, user_id " + user_id);
		newfriends_list = ctrl_relation.pGetRelationList(user_id, Constants.RELATION_ACCEPT_CONFIRM);
		Log.e(TAG, "newfriends_list.size = " + newfriends_list.size());
		// 获得好友列表
		Log.e("pScrMain", "获取 好友 列表数据, user_id " + user_id);
		friends_list = ctrl_relation.pGetRelationList(user_id, Constants.RELATION_BOTH_CONFIRM);
		Log.e(TAG, "friend_list = " + friends_list.size());
		
		Log.e(TAG, "好友数据获取完毕，给handler 发送消息，进行数据填充");
		handler.sendEmptyMessage(showFriendsInterface_signal);
	}
	
	/*
	 * 添加好友 - pCB02F07
	 * 在好友列表标签页点击添加好友的按钮，系统跳转至邀请好友界面
	 */
	public void pAddFriends() {
		Intent intent = new Intent();
		intent.setClass(pScrMain.this, pInviteFriend.class);
		this.startActivity(intent);
	}
	
	/*
	 * 确认活动邀请 - pCB02F08
	 */
	public void pConfirmEventInvite() {
		ctrl_event.pConfirmInvitation(user_id, current_event_id);
		handler.sendEmptyMessage(confirmEventInvite_signal);
	}
	
	/*
	 * 确认好友邀请 - pCB02F09
	 */
	public void pConfirmFriendsInvite() {
		//int 好友关系id = 获得该条邀请的id;
		ctrl_relation.pConfirmRelation(confirmFriendsInvite_relation);	//好友关系管理类.确认好友邀请();
		handler.sendEmptyMessage(confirmFriendInvite_signal);
	}
	
	/*
	 * 创建新活动 - pCB02F10
	 * 在活动列表标签页点击创建新活动的按钮，系统跳转至活动信息界面
	 */
	public void pNewEvent() {
		Log.e("pScrMain", "pNewEvent ---");
		Intent intent = new Intent();
		intent.setClass(pScrMain.this, pScrEventInfo.class);
		
		Bundle data = new Bundle();
		data.putInt("EVENT_ID", -1);
		intent.putExtras(data);
		//this.setResult(this.RESULT_OK, intent);
		startActivityForResult(intent, ScrEventInfo);
		//this.startActivity(intent);
	}
	
	/*
	 * 修改活动信息 - pCB02F11
	 * 在活动列表标签页长按某条活动弹出的菜单中选择修改活动信息，系统跳转至活动信息界面
	 */
	public void pAlterEvent() {
		Log.e(TAG, "修改活动pAlertEvent");
		Intent intent = new Intent();
		Log.e(TAG, "EVENT_ID = " + current_event_id);
		intent.setClass(pScrMain.this, pScrEventInfo.class);
		intent.putExtra("EVENT_ID", current_event_id);
		startActivityForResult(intent, ScrEventInfo);
		//this.startActivity(intent); 
	}
	
	/*
	 * 取消活动 - pCB02F12
	 * 在活动列表标签页长按某条活动弹出的菜单中选择取消活动，系统弹出确认对话框，点击确定则取消活动并刷新活动列表，点击返回则不取消活动。
	 */
	public void pCancelEvent() {
		ctrl_event.pEventStateChange(current_event_id, Constants.EVENT_STATE_CANCELLED);
		handler.sendEmptyMessage(cancelEvent_signal);
	}
	
	/*
	 * 进入活动主界面 - pCB02F13
	 * 在活动列表标签页或历史列表标签页点击某条活动，系统跳转至活动主界面
	 */
	public void pGotoEventMain(pTableEventInfo event) {
		Intent intent = new Intent();
		// 暂时跳转到活动信息界面，本来应该跳转到活动主界面 
		intent.setClass(pScrMain.this, pScrEventMap.class);
		Bundle data = new Bundle();
		data.putInt("CURRENT_EVENT_ID", current_event_id);
		data.putInt("CURRENT_EVENT_OWNER_ID", event.getpEventOwnerId());
		intent.putExtras(data);
		this.startActivity(intent);
	}
	
	/*
	 * 订阅相关主题
	 */
	public void pSubscribe(String topic) {
		//Log.e("pScrMain","pSubscribe topic = " + topic);
		PushService.actionSubTopics(topic);
	}
	
	/*
	 * 针对pTableEventInfo的布适配器
	 * 传递的参数有数据list和布局资源id
	 */
	class EventLVAdapter extends BaseAdapter {
		// inflater用于将一个XML文件转换成一个视图（View)
		private int layout_id;
		private LayoutInflater inflater;
		private LinkedList<pTableEventInfo> list;
		public EventLVAdapter(Context context, LinkedList<pTableEventInfo> list, int layout_id) {
			inflater = LayoutInflater.from(context);
			this.list = list;
			this.layout_id = layout_id;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = inflater.inflate(layout_id, null);
			TextView pLabelLocationName, pLabelEventStart, pLabelEventOwner;
			ImageView pImgConfirmInvite;
			// 获得pTableEventInfo需要添加final修饰符，否则onClick事件中的event将不是当前的event
			final pTableEventInfo event = (pTableEventInfo) this.getItem(position);
			switch(layout_id) {
			case R.layout.scrmain_event_new_event_item :
				//Log.e("pScrMain", "R.layout.event = scrmain_event_new_event_item");
				pLabelLocationName = (TextView) view.findViewById(R.id.byname);
				pLabelEventStart = (TextView) view.findViewById(R.id.date);
				pLabelEventOwner = (TextView) view.findViewById(R.id.owner);
				pImgConfirmInvite = (ImageView) view.findViewById(R.id.confirm_event_flag);
				pImgConfirmInvite.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// 设置当前确认邀请的id，传给pConfirmEventInvite处理
						event_interface_reflash = true;
						current_event_id = event.get_id();
						switch_func_thread = new SwitchFuncThread(confirmEventInvite_signal);
						switch_func_thread.start();
					}
				});
				//当打开时，订阅相关的主题
				pSubscribe(PushService.MQTT_TOPIC + "/event_" + event.get_id());
				pSubscribe(PushService.MQTT_TOPIC + "/event_" + event.get_id() + "/geo");
				
				pLabelLocationName.setText("地点：\t\n\t" + 
						org.apache.commons.lang.StringEscapeUtils.unescapeJava(event.getpEventByname()));
				pLabelEventStart.setText("时间：\t\n\t" + event.getpEventStart().substring(5, 9));
				pLabelEventOwner.setText("发起人：\t\n\t"+event.getpEventOwnerId());
				break;
			case R.layout.scrmain_event_rolling_event_item :
				pLabelLocationName = (TextView) view.findViewById(R.id.byname);
				pLabelEventOwner = (TextView) view.findViewById(R.id.owner);
				pLabelLocationName.setText("地点：\t\n\t" + 
						org.apache.commons.lang.StringEscapeUtils.unescapeJava(event.getpEventByname()));
				pLabelEventOwner.setText("发起人：\t\n\t"+event.getpEventOwnerId());
				break;
			case R.layout.scrmain_event_unstart_event_item :
				pLabelLocationName = (TextView) view.findViewById(R.id.byname);
				pLabelEventStart = (TextView) view.findViewById(R.id.date);
				pLabelEventOwner = (TextView) view.findViewById(R.id.owner);
				pLabelLocationName.setText("地点：\t\n\t" + 
						org.apache.commons.lang.StringEscapeUtils.unescapeJava(event.getpEventByname()));
				pLabelEventStart.setText("时间：\t\n\t" + event.getpEventStart().substring(5, 9));
				pLabelEventOwner.setText("发起人：\t\n\t"+event.getpEventOwnerId());
				break;
			case R.layout.scrmain_history_finish_event_item :
				Log.e("pScrMain", "R.layout.history = ");
				pLabelLocationName = (TextView) view.findViewById(R.id.finish_byname);
				pLabelEventStart = (TextView) view.findViewById(R.id.finish_date);
				pLabelEventOwner = (TextView) view.findViewById(R.id.finish_owner);
				pLabelLocationName.setText("地点：\t\n\t" + 
						org.apache.commons.lang.StringEscapeUtils.unescapeJava(event.getpEventByname()));
				pLabelEventStart.setText("时间：\t\n\t" + event.getpEventStart().substring(5, 9));
				pLabelEventOwner.setText("发起人：\t\n\t"+event.getpEventOwnerId());
				break;
			case R.layout.scrmain_history_cancel_event_item :
				pLabelLocationName = (TextView) view.findViewById(R.id.cancel_byname);
				pLabelEventStart = (TextView) view.findViewById(R.id.cancel_date);
				pLabelEventOwner = (TextView) view.findViewById(R.id.cancel_owner);
				pLabelLocationName.setText("地点：\t\n\t" + 
						org.apache.commons.lang.StringEscapeUtils.unescapeJava(event.getpEventByname()));
				pLabelEventStart.setText("时间：\t\n\t" + event.getpEventStart().substring(5, 9));
				pLabelEventOwner.setText("发起人：\t\n\t"+event.getpEventOwnerId());
				break;
			default :
				break;
			}
			/*view.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					// TODO Auto-generated method stub
					event_interface_reflash = true;
					current_event_id = event.get_id();
					return false;
				}
			});*/
			return view;
		}
	}
	
	/*
	 * 针对pTableRelation的布适配器
	 * 传递的参数有数据list和布局资源id
	 */
	class FriendLVAdapter extends BaseAdapter {
		// inflater用于将一个XML文件转换成一个视图（View)
		private int layout_id;
		private LayoutInflater inflater;
		private LinkedList<pTableRelation> list;
		public FriendLVAdapter(Context context, LinkedList<pTableRelation> list, int layout_id) {
			inflater = LayoutInflater.from(context);
			this.list = list;
			this.layout_id = layout_id;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = inflater.inflate(layout_id, null);
			TextView pLabelFriendName;
			ImageView pImgConfirmInvite;
			final pTableRelation relation = (pTableRelation) this.getItem(position);
			switch(layout_id) {
			case R.layout.scrmain_friend_new_friends_item :
				pImgConfirmInvite = (ImageView) view.findViewById(R.id.confirm_friend_flag);
				pImgConfirmInvite.setOnClickListener(new ImageView.OnClickListener(){
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						friend_interface_reflash = true;
						confirmFriendsInvite_relation = relation;
						switch_func_thread = new SwitchFuncThread(confirmFriendInvite_signal);
						switch_func_thread.start();
					}
				});
				pLabelFriendName = (TextView) view.findViewById(R.id.new_friend_name);
				pLabelFriendName.setText("新朋友：\t\n\t" + relation.getpFriendId() + " id = " + relation.get_id());
				break;
			case R.layout.scrmain_friend_friends_item :
				pLabelFriendName = (TextView) view.findViewById(R.id.friend_name);
				pLabelFriendName.setText("好友：\t\n\t"+relation.getpFriendId());
				break;
			default :
				break;
			}
			return view;
		}
	}
	/*public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		if (listTag.contains(getItem(position))) {
			view = LayoutInflater.from(getContext()).inflate(
					R.layout.group_list_item_tag, null);
		} else {
			view = LayoutInflater.from(getContext()).inflate(
					R.layout.group_list_item, null);
		}
		TextView textView = (TextView)view.findViewById(R.id.group_list_item_text);
		textView.setText(getItem(position));
		return view;
	}*/
	
	/*
	 * 各个功能的后台数据交互都在这个线程中启动
	 * 根据所传递不同的信号，调用不同的方法
	 */
	class SwitchFuncThread extends Thread {
		private int signal;
		private String topic;
		public SwitchFuncThread(int signal) {
			this.signal = signal;
		}
		public SwitchFuncThread(int signal, String topic) {
			this.signal = signal;
			this.topic = topic;
			Log.e("pScrMain", "switch constructor topic  = " + topic);
		}
		public void run() {
			switch (signal) {
			case  showEventInterface_signal :
				pShowEventList();
				break;
			case showFriendsInterface_signal :
				pShowFriendsList();
				break;
			case showHistoryInterface_signal :
				pShowHistoryList();
				break;
			case confirmEventInvite_signal :
				pConfirmEventInvite();
				break;
			case confirmFriendInvite_signal :
				pConfirmFriendsInvite();
				break;
			case cancelEvent_signal :
				pCancelEvent();
				break;
			case subscribe_signal :
				Log.e("pScrMain", "switch to func thread subscribe ");
				pSubscribe(topic);
				break;
			default :
				break;
			}
		}
	}
	
	public void setListViewHeightBasedOnChildren(ListView listView) {
        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
               return;
        }
       
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {   //listAdapter.getCount()返回数据项的数目
               View listItem = listAdapter.getView(i, null, listView);
               listItem.measure(0, 0);  //计算子项View的宽高
               totalHeight += listItem.getMeasuredHeight();  //统计所有子项的总高度
        }
       
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        //listView.getDividerHeight()获取子项间分隔符占用的高度
        //params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
	}
	
	/*
	 * 处理增加长按弹出菜单
	 */
	@Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        menu.setHeaderTitle("菜单");
    }
	
	@Override
    public boolean onContextItemSelected(MenuItem item) {
        //AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
        case R.id.modify_item:
        	Log.e(TAG, "修改活动");
        	pAlterEvent();
            return true;
        case R.id.cancel_item:
        	showDialog(CONFIRM_CANCEL_DIALOG);
        	return true;
        default:
            return super.onContextItemSelected(item);
        }
    }
	
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case CONFIRM_CANCEL_DIALOG:
            if (confirmCancelDialog == null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);      
                builder.setMessage("确定要取消该活动吗？");
                builder.setCancelable(true);
                builder.setPositiveButton("是", cancelEventConfirmationListener());
                builder.setNegativeButton("否", cancelListener());
                confirmCancelDialog = builder.create();
            }
            return confirmCancelDialog;
        default:
            Log.e("pScrMain", "Attempting to create an unkonwn dialog with an id of " + id);
            return null;
        }
    }
	
	protected DialogInterface.OnClickListener cancelEventConfirmationListener() {
        return new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            	event_interface_reflash = true;
            	history_interface_reflash = true;
            	switch_func_thread = new SwitchFuncThread(cancelEvent_signal);
        		switch_func_thread.start();
            }
        };
    }

    protected DialogInterface.OnClickListener cancelListener() {
        return new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        };
    }
    
    /*
     * ListView的单击事件处理
     * 单击获取
     */
    private OnItemClickListener click_listener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> av, View v, int position,
				long time) {
			// TODO Auto-generated method stub
			Log.e("pScrMain", "on item click av = " + av.toString());
			if (av == pListNewInvite){
				current_event_id = unconfirm_list.get(position).get_id();
				current_event = unconfirm_list.get(position);
			} else if (av == pListRolling){
				current_event_id = rolling_list.get(position).get_id();
				current_event = rolling_list.get(position);
			} else if (av == pListUnstarted) {
				current_event_id = unstart_list.get(position).get_id();
				current_event = unstart_list.get(position);
			} else if (av == pListFinished) {
				current_event_id = finished_list.get(position).get_id();
				current_event = finished_list.get(position);
			} else if (av == pListCancelled){
				current_event_id = cancelled_list.get(position).get_id();
				current_event = cancelled_list.get(position);
			}
			Log.e("pScrMain", "被点击的活动id = " + current_event_id);
			pGotoEventMain(current_event);
		}
	};
	
	/*
	 * ListView的长按事件处理
	 */
	
	private OnItemLongClickListener longclick_listener = new AdapterView.OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> av, View v,
				int position, long id) {
			// TODO Auto-generated method stub
			event_interface_reflash = true;
			if (av == pListNewInvite) {
				current_event_id = unconfirm_list.get(position).get_id();
			} else if (av == pListRolling) {
				current_event_id = rolling_list.get(position).get_id();
			} else if (av == pListUnstarted) {
				current_event_id = unstart_list.get(position).get_id();
			} 
			Log.e("pScrMain", "long，被点击的活动id = " + current_event_id);
			return false;
		}
	};
}
